package com.sd.repay.controller;

import com.alibaba.fastjson.JSONObject;
import com.sd.repay.pojo.SmsInfo;
import com.sd.repay.service.SmsService;
import com.sd.repay.utils.Md5Util;
import com.sd.repay.utils.StringUtil;
import com.sd.repay.utils.WebUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 短信
 *
 * @author
 */
@Controller
@RequestMapping(value = "/sms")
public class SmsController {
    private final Logger log = LoggerFactory.getLogger(SmsController.class);
    @Autowired
    private SmsService smsRoute;

    /*@Resource
    private SmsRouteService smsRoute;*/
    private final int phoneMaxLength = 11;
    private final int businessMaxLength = 32;

    /**
     * 验证码校验
     *
     * @param params
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/checkCode")
    public void checkCode(@RequestParam Map<String, String> params, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain; charset=utf-8");
        JSONObject result = new JSONObject();
        String phone = params.get("phone");
        String valiCode = params.get("valiCode");
        String sms_business = params.get("sms_business");
        String sign = params.get("sign");
        /**
         * 基础校验
         */
        if (StringUtil.isBlank(phone, sign, valiCode, sms_business)) {
            result.put("rep_status", "1");
            result.put("msg", "短信验证失败,请求缺少必要参数!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        /**
         * 格式校验
         */
        if (phone.length() != phoneMaxLength) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,无效手机号!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        if (sms_business.length() > businessMaxLength) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,无效业务代码!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }


        /**
         * 签名校验
         */
        String smsKey = WebUtil.getSysValue("SMS_API_KEY");
        String signStr = Md5Util.MD5Encode(phone + valiCode + sms_business + smsKey, "UTF-8", false);
        if (!signStr.equalsIgnoreCase(sign)) {
            result.put("rep_status", "1");
            result.put("msg", "短信发送失败,秘钥校验错误!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        SmsInfo smsInfo = new SmsInfo();
        smsInfo.setMobiles(phone);
        smsInfo.setSms_business(sms_business);
        smsInfo.setVali_code(valiCode);
        smsRoute.checkValidateCode(smsInfo);
        if ("2".equals(smsInfo.getVali_status())) {
            result.put("rep_status", "2");
            result.put("check_status", "2");
            result.put("msg", "校验成功!");
            log.info("验证码请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }
        result.put("rep_status", "2");
        result.put("check_status", "1");
        result.put("msg", "校验失败!");
        log.info("验证码请求[{}]系统响应[{}]", params.toString(), result.toString());
        response.getWriter().write(result.toString());
        return;
    }

    /**
     * 发送短信
     *
     * @param params
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/smsSend")
    public void smsSend(@RequestParam Map<String, String> params, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain; charset=utf-8");
        JSONObject result = new JSONObject();
        String phone = params.get("phone");
        String sms_business = params.get("sms_business"); //业务代码自定义上传
        String source = params.get("source");
        String sms_content = params.get("sms_content");
        String sms_type = params.get("sms_type"); //短信类型 1.验证码 2.自定义通知
        String sign = params.get("sign");
        String reqIp = StringUtil.getIpAddr(request);
        log.info("新的短信请求[{}]IP地址[{}]", params.toString(), reqIp);
        /**
         * 基础校验
         */
        if (StringUtil.isBlank(phone, sms_business, sms_type, source, sign)) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,请求缺少必要参数!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        /**
         * 业务要素校验
         */
        if (!"1".equals(sms_type) && StringUtil.isEmpty(sms_content)) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,发送内容为空!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        /**
         * 格式校验
         */
        if (phone.length() != phoneMaxLength) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,无效手机号!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        int contentMaxLength = 200;
        if (!StringUtil.isEmpty(sms_content) && sms_content.length() > contentMaxLength) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,短信内容超出限制：" + contentMaxLength);
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        if (sms_business.length() > businessMaxLength) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,业务代码超出长度限制!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        if (sms_type.length() > 2) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,未知短信类型!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }


        /**
         * 签名校验
         */
        String key = WebUtil.getSysValue("SMS_API_KEY");
        String signStr = Md5Util.MD5Encode(phone + sms_business + sms_type + source + key, "UTF-8", false);
        if (!signStr.equalsIgnoreCase(sign)) {
            result.put("status", "1");
            result.put("msg", "短信发送失败,秘钥校验错误!");
            log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
            response.getWriter().write(result.toString());
            return;
        }

        /**
         * IP黑名单校验
         */
        String blackList = WebUtil.getSysValue("SMS_BLACK_IP");
        if (!StringUtil.isBlank(blackList)) {
            String[] blackIp = blackList.split(",");
            for (String ip : blackIp) {
                if (ip.equals(reqIp)) {
                    result.put("status", "1");
                    result.put("msg", String.format("短信发送失败，IP:%s 已列入短信黑名单!", reqIp));
                    log.info("短信请求[{}]系统响应[{}]", params.toString(), result.toString());
                    response.getWriter().write(result.toString());
                    return;
                }
            }
        }

        SmsInfo smsInfo = new SmsInfo();
        smsInfo.setMobiles(phone);
        smsInfo.setSms_content(sms_content);
        smsInfo.setSource_system(source);
        smsInfo.setSms_type(sms_type); //短信类型 1.验证码 2.自定义通知
        smsInfo.setSms_business(sms_business); //短信验证业务代码
        smsRoute.smsSend(smsInfo);
        String tempStatus = smsInfo.getSms_status();
        String rep_status = "";
        String rep_msg = "";
        //短信发送状态  1.未发送 2.已发送 3.发送失败 4.发送成功 6.未知
        //响应 status：状态  1.失败 2成功
        if ("1".equals(tempStatus) || "3".equals(tempStatus)) {
            rep_status = "1";
            rep_msg = "发送失败";
        } else {
            rep_status = "2";
            rep_msg = "发送成功";
        }

        result.put("status", rep_status);
        result.put("msg", rep_msg);
        /*result.put("status", smsInfo.getSms_status());
        result.put("msg", smsInfo.getSms_rsp_msg());*/
        log.info("手机号[{}]短信请求原文：{} 执行完成，系统响应:{}", new Object[]{phone, params.toString(), result.toJSONString()});
        response.getWriter().write(result.toString());
        return;
    }

}
